<?php
/**
 * Add a new User in the system
 */

use Fox\Generator;
use Fox\Html\Screen;

$xview = Xview::instance();
if (!Fox\Authorization\Manager::check('Users-Create'))
{
	$xview->accessDenied();
}

$idusr = $xview->val("idusr");

try {
	$user = new User($idusr);
	$data = $user->getData();
	$data['op_entity'] = $user->getPrefs('op_entity',true);
}
catch (Fox\Object\Exception\NotExist $e)
{
	Xview::instance()->systemError();
}
if(!$user->exists())
{
	Xview::instance()->systemError();
}

$screen = new Screen('eUser','update');
// Check if password can be reset first
if($xview->passwordCanBeReset())
{
	$screen->toolbar()->add(new Fox\Html\Button("ipass",
										Generator::display('initpass',
											Generator::url("users",
															"ipass",
															null,
															array('idusr' => $idusr)))));
}
// Remove User From the application (it does not delete the user)
$screen->toolbar()->add(new Fox\Html\Button("remove",
									Generator::display('remove',
											Generator::url("users",
															"apps",
															"remove",
															array('value' => $idusr))),
									Msg("users",47))
									);
// Header Information
$block = Xview::instance()->component("users","headInfo");
$screen->add($block);

// Preferences
$blpref = Xview::instance()->component("users","preferences");
$screen->add($blpref);

// Preferences
$blAdd = Xview::instance()->component("users","customDataInfo");
if(!empty($blAdd))
	$screen->add($blAdd);

$screen->initialize($data);

if($screen->submitted())
{
	$inputs = $screen->get();
	if(!$screen->errors())
	{
		// Check Duplicates
		$finder = new User();
		$fragments[] = new Fox\Dao\SqlFragment("LOWER(email) = LOWER(?)",array($inputs['email']));
		$fragments[] = new Fox\Dao\SqlFragment("idusr != ?",array($idusr));
		$res = $finder->find($fragments);
		if (count($res) > 0)
		{
			Fox\Message::Error(Msg(User::BUNDLE_NAME,3,$inputs['email']));
		}
	}
	if(!$screen->errors())
	{
		try {
			$user->setFields($inputs);
			$user->update();
			$user->updateWebApps($xview->id(),$inputs['proid']);
			// Set Prefs
			$user->SetPrefs("op_entity", $inputs['op_entity']);
			// Attach the current application to the user
			Fox\Message::Success(Msg(Fox\Msg::BUNDLE,Fox\Msg::MSG_UPDATE,$user->email));
			$xview->redirect('?mod=users&act=upd&idusr='.$user->getId());
		}
		catch (Fox\Object\Exception\Save $e)
		{
			Fox\Core\Errors::pushMessage($e);
		}
	}
}
echo $screen->Display();